package com.gourd.common.aspect;

import com.alibaba.fastjson.JSON;
import com.gourd.common.exception.ServiceException;
import com.gourd.common.utils.RedisUtil;
import com.gourd.common.utils.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
/**
 * @功能描述 aop解析注解
 * @author gourd
 * @date 2018-08-26
 */
@Slf4j
public class NoRepeatSubmitAop {

    private static final String JWT_TOKEN_KEY = "jwt-token";

    @Autowired
    private RedisUtil redisUtil;


    @Pointcut("@annotation(com.gourd.common.annotation.NoRepeatSubmit)")
    public void serviceNoRepeat() {
    }

    @Around("serviceNoRepeat()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        HttpServletRequest request = RequestHolder.getRequest();
        String jwtToken = request.getHeader(JWT_TOKEN_KEY);
        String key = jwtToken + "-" + request.getServletPath()+JSON.toJSONString(request.getParameterMap());
        if (redisUtil.get(key) == null) {
            Object o = pjp.proceed();
            // 2秒内统一用户同一个地址同一个参数，视为重复提交
            redisUtil.setExpire(key, "0",2L);
            return o;
        } else {
            log.error("重复提交");
            throw new ServiceException("重复提交");
        }
    }

}